﻿using D3StatsClient.Commands;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Deployment.Application;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Xml.Linq;

namespace D3StatsClient.ViewModel
{
    public class SessionPickerEntry : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public string Name { get; set; }
        public string StartTime { get; set; }
        public string EndTime { get; set; }
        public string Played { get; set; }
        public string TotalDrops { get; set; }
        public string XmlDataFile { get; set; }

        private bool _isUploading = false;
        public bool IsUploading
        {
            get
            {
                return _isUploading;
            }
            set
            {
                _isUploading = value;
                this.OnPropertyChanged("IsUploading");
            }
        }

        private bool _isUploaded = false;
        public bool IsUploaded
        {
            get
            {
                return _isUploaded;
            }
            set
            {
                _isUploaded = value;
                this.OnPropertyChanged("IsUploaded");
            }
        }

        protected void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }
    }

    public class SessionPickerWindowViewModel : ViewModelBase
    {
        public ICommand LoadSessionCommand { get; set; }
        public ICommand DeleteSessionCommand { get; set; }
        public ICommand OpenSessionsFolderCommand { get; set; }
        public ICommand UploadSessionCommand { get; set; }

        public SessionPickerWindowViewModel()
        {
            LoadSessionCommand = new LoadSession();
            DeleteSessionCommand = new DeleteSession();
            OpenSessionsFolderCommand = new OpenSessionsFolder();
            UploadSessionCommand = new UploadSession();

            Sessions = new ObservableCollection<SessionPickerEntry>();

            Task.Factory.StartNew(() =>
            {
                this.ProvisionSessionCollection();
            });
            
        }

        public void Refresh()
        {
            Task.Factory.StartNew(() =>
            {
                Dispatcher.Invoke(new Action(() =>
                {
                    this.Sessions.Clear();
                }));

                
                this.ProvisionSessionCollection();
            });
        }

        private void ProvisionSessionCollection()
        {
            string folderPath = string.Empty;

            if (ApplicationDeployment.IsNetworkDeployed)
            {
                folderPath = string.Format("{0}\\{1}", ApplicationDeployment.CurrentDeployment.DataDirectory, Properties.Settings.Default.XMLStatsContainer);
            }
            else
            {
                folderPath = string.Format("{0}", AppDomain.CurrentDomain.BaseDirectory + Properties.Settings.Default.XMLStatsContainer);
            }

            if (Directory.Exists(folderPath))
            {
                foreach (string file in Directory.EnumerateFiles(folderPath, "*.stats"))
                {
                    try
                    {
                        XDocument doc = XDocument.Load(file);

                        //Load main data
                        SessionPickerEntry pe = new SessionPickerEntry();

                        if (doc.Element("items").Attribute("IsUploaded") != null)
                        {
                            pe.IsUploaded = bool.Parse(doc.Element("items").Attribute("IsUploaded").Value);
                        }
                        else
                        {
                            pe.IsUploaded = false;
                        }

                        pe.Name = doc.Element("items").Attribute("sessionname").Value;
                        pe.StartTime = DateTime.Parse(doc.Element("items").Attribute("starttime").Value).ToLocalTime().ToString();
                        pe.EndTime = DateTime.Parse(doc.Element("items").Attribute("endtime").Value).ToLocalTime().ToString();
                        pe.TotalDrops = doc.Descendants("item").Count().ToString();

                        //Calculate the time played for this session.
                        DateTime start = DateTime.Parse(pe.StartTime);
                        DateTime stop = DateTime.Parse(pe.EndTime);

                        TimeSpan played;

                        if (doc.Element("items").Attribute("played").Value != null)
                        {
                            played = TimeSpan.Parse(doc.Element("items").Attribute("played").Value);
                        }
                        else
                        {
                            played = stop - start;
                        }

                        pe.Played = played.ToString("dd\\:hh\\:mm\\:ss");

                        pe.XmlDataFile = file;

                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            Sessions.Add(pe);
                        })); 
                    }
                    catch (Exception ex)
                    {
                        Logging.Logger.Log(string.Format("session stats document {0} has invalid data. Error was : {1}", file, ex.Message));
                    }
                   
                }
            }
        }

        public SessionPickerEntry SelectedSession
        {
            get { return (SessionPickerEntry)GetValue(SelectedSessionProperty); }
            set { SetValue(SelectedSessionProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedSession.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedSessionProperty =
            DependencyProperty.Register("SelectedSession", typeof(SessionPickerEntry), typeof(SessionPickerWindowViewModel), new PropertyMetadata(null));

        

        public ObservableCollection<SessionPickerEntry> Sessions
        {
            get { return (ObservableCollection<SessionPickerEntry>)GetValue(SessionsProperty); }
            set { SetValue(SessionsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Sessions.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SessionsProperty =
            DependencyProperty.Register("Sessions", typeof(ObservableCollection<SessionPickerEntry>), typeof(SessionPickerWindowViewModel), new PropertyMetadata(null));

        
    }
}
